# -*- coding: utf-8 -*-
#!/usr/bin/python
#FileName:bugfree_bak.py
#python v2.6 for Linux
#@by RT-Boy
#email: tsbc@vip.qq.com
#date: 2012-02-15
import os
import time
import sys
from ftplib import FTP	# 引入FTP库

backupdir = "/tmp/bugfree_bak"		# 定义文件备份目录
path1 = "/opt/lampp/var/mysql"		# 备份源文件路径1
path2 = "/opt/lampp/htdocs/bugfree/BugFile"		# 备份源文件路径2
source = path1,path2	# 备份目标文件路径
print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++ "
print "|==============     backup---file     ==================|"
print "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
print " "
if not os.path.exists(backupdir):		#判断备份目录是否存在，如果不存就创建一个。
	print backupdir + " does not exists,will create a new !"
	print "---------------------------------------------------------"
	os.mkdir(backupdir)
	print ":::::: Successflly created directory %s ::::::" % (backupdir)
	print "---------------------------------------------------------"

#列出备份目录下所有文件路径，文件夹、文件名词。
#for dirpath,dirnames,filenames in backupdir:		
#	for dirname in dirnames:
#		print "dirpath is:" + dirpath
#		print "dirname is:" + dirname
#	for filename in filenames:
#		print "dirpath is:" + dirpath
#		print "filename with full path is:"+os.path.join(dirpath,filename)

#定义备份方法 [参数1 文件备份目录][参数2 源文件路径source[]是两个路径的数组 source[0],source[1]]
def backupd(backupdir,source):
	Server = '192.168.0.110'	# 定义FTP服务器地址
	UserName = ''			# 定义FTP登陆用户名（为空则为匿名）
	PassWord = ''			# 定义FTP登陆密码   （为空则为匿名）
	today = time.strftime('%Y%m%d')		#取出当前年月日
	now = time.strftime('%H%M%S')		#取出当前时分秒
	yesterday = time.strftime('%Y%m%d',time.localtime(time.time() - 24*60*60)) # 取出昨天的时间
	target1 = today+'.tar.gz'		# 定义今天压缩包生成的文件名。
	target2 = yesterday+'.tar.gz'	# 定义昨天压缩包生成的文件名。
	bakname = backupdir+'/'+target1 # 备份文件的全路径 
	remotepath = '/bf_updata'	# 定义FTP上传的目录
	#判断自动生成一个以当天日期为名的文件夹
	# if not os.path.exists(backupdir+'/'+today):
		# print today+" directory does not exists,will create a new!"
		# print "---------------------------------------------------------"
		# os.mkdir(backupdir+'/'+today)
		# print ":::::: successflly created directory %s ::::::" % (today)
		# print "---------------------------------------------------------"
	for files in source:
		if os.path.isdir(files) == True:	# 判断备份源路径 path1 path2 是否存在
			tar_command="tar -czf %s %s %s" %(bakname,source[0],source[1]) # 如果目录存在，那么就指定要执行的打包命令。
		else:
			print ">>>>>"+files+"is not the Directory!"
			print " "
			print ">>>>>:::::: Backup Failed ::::::"
			sys.exit()
	if os.path.isfile(backupdir+'/'+target2) == True:	# 判断昨天的备份文件是否存在 
		try:
			os.remove(backupdir+'/'+target2) # 如果存在则删除
		except:
			print ">>>>>Failed to delete localhost old files"
			print " "
	else:
		print ">>>>>Localhost old file is not extis"
		print " "
	if os.system(tar_command) == 0: # 进行打包备份成功则提示备份成功，打包出现异常，则退出，备份失败。
		print ":::::: Successful backup! ::::::"
		print " "
		print "Flie Path: %s" % (backupdir+'/'+target1)
		print " "
		print "ooooooooo=Upload FTP %s=ooooooooo" % (Server) # 把备份文件上传到FTP
		print " "
		f = FTP(Server)		# 连接服务器Server=FTP服务器的IP端口默认21
		try:
			f.login(UserName,PassWord) # 使用用户名密码登陆，为空匿名用户登陆
		except:	# 登陆失败抛出异常
			print ">>>>>Login Failed"
			print " "
			print ">>>>>FTP upload Failed....."
			sys.exit()		
		else:
			print "Welcome:",f.getwelcome() # 登陆成功获取ftp的welcome版本等信息。
			print " "
		try:
			f.cwd(remotepath) # 进入到ftp的（remotepath）自定义目录下
		except:				# 如果没能正常进入目录则抛出异常，进入目录失败。
			print ">>>>>Into the directory failed"  
			print " "
			print ">>>>>FTP upload Failed...."
			sys.exit()
		else:
			delfile =  yesterday+'.tar.gz' # 定义昨天已经好备份的文件名称
			try:
				f.delete(delfile)	# 删除昨天的备份文件
			except:		# 删除旧文件失败抛出异常
				print ">>>>>Failed to delete FTP old files"
		localfile = open(bakname,'rb') # 读取要备份上传文件的全路径
		bakfile = os.path.basename(bakname)	# 获得文件的名称 
		try:
			f.storbinary('STOR %s' % bakfile,localfile) # 以二进制格式上传文件到FTP
		except:	# 上传出错抛出异常，上传失败
			print " "
			print ">>>>>FTP upload Failed!"
		else:	# 否则上传成功
			print " "
			print "FTP upload Success!"
		localfile.close() # 关闭打开读取的文件
		f.quit()	#  退出FTP
		sys.exit()	# 程序退出
	else:
		print ">>>>>:::::: Backup Failed ::::::"
		print " "
		sys.exit()
backupd(backupdir,source)
